#include <iostream>
#include <shared_mutex>
#include <thread>
#include <vector>

std::shared_mutex rwMutex;
int data = 0;  								// 共享数据

void reader(int id) {
    for (int i = 0; i < 5; ++i) {
        rwMutex.lock_shared();  				// 获取共享锁
        std::cout << "Reader " << id << " reads " << data << '\n';
        rwMutex.unlock_shared();  				// 释放共享锁
        std::this_thread::sleep_for(std::chrono::milliseconds(100));  // 模拟读取所需时间
    }
}

void writer(int id) {
    for (int i = 0; i < 5; ++i) {
        rwMutex.lock();  						// 获取独占锁
        data += id;
        std::cout << "Writer " << id << " writes " << data << '\n';
        rwMutex.unlock();  					// 释放独占锁
        std::this_thread::sleep_for(std::chrono::milliseconds(100));  // 模拟写入所需时间
    }
}

int main() {
    std::thread w(writer, 10), r1(reader, 1), r2(reader, 2);

    w.join();
    r1.join();
    r2.join();

    return 0;
}